package com.liuyk.commonlib.fragment;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.liuyk.commonlib.R;

/**
 * 支持加载状态和下拉刷新的fragment
 * <p>
 * Created by liuyk on 2019/11/10.
 */
public abstract class BaseSwipeRefreshLoadingFragment extends BaseLoadingFragment implements SwipeRefreshLayout.OnRefreshListener {

    private SwipeRefreshLayout mSwipeRefreshLayout;

    @Override
    protected View getContentView(LayoutInflater inflater, ViewGroup container) {
        View view = super.getContentView(inflater, container);
        setLoadingContent(R.layout.base_swipe_refresh_loading_layout);

        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh);
        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.BLUE);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        return view;
    }

    protected void setSwipeRefreshLoadingContent(int resId) {
        final View contentView = LayoutInflater.from(getActivity()).inflate(resId, mSwipeRefreshLayout, false);
        setSwipeRefreshLoadingContent(contentView);
    }

    protected void setSwipeRefreshLoadingContent(View view) {
        mSwipeRefreshLayout.addView(view);
    }

    @Override
    public void onRefresh() {
        refresh();
    }

    //pull refresh
    protected abstract void refresh();

    protected boolean isRefreshing() {
        return mSwipeRefreshLayout.isRefreshing();
    }

    protected void stopRefresh() {
        if (isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    protected void startRefresh() {
        if (!isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
    }
}
